package com.wyz.socket.test.client;


import com.wyz.socket.core.base.Context;
import com.wyz.socket.core.impl.chain.AbstractStringPacketChain;
import com.wyz.socket.core.impl.ConnectorHandler;
import com.wyz.socket.core.base.packet.string.StringReceivePacket;
import com.wyz.socket.core.impl.scheduler.IdleTimeoutSchedulerJob;
import com.wyz.socket.core.impl.scheduler.SchedulerJob;
import com.wyz.socket.core.utils.Log;

import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;

public class TCPClient extends ConnectorHandler {

    public TCPClient(SocketChannel socketChannel , File cacheFile) throws IOException {
        super(socketChannel , cacheFile);
        getPrintChain().addChain(new AbstractStringPacketChain() {
            @Override
            protected boolean consume(ConnectorHandler handler, StringReceivePacket stringReceivePacket) {
                String msg = stringReceivePacket.entity();
                Log.printlnInfo("Client" , "PrintStringPacketChain : "+msg);
                return true ;
            }
        });
        SchedulerJob job = new IdleTimeoutSchedulerJob(60, TimeUnit.SECONDS, this);
        job.scheduler(Context.get().getScheduler());
    }

    public static TCPClient startWith(ServerInfo info , File file) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(Inet4Address.getByName(info.getAddress()), info.getPort()));
        System.out.println("已发起服务器连接，并进入后续流程～");
        System.out.println("客户端信息：" + socketChannel.getLocalAddress().toString());
        System.out.println("服务器信息：" + socketChannel.getRemoteAddress().toString());
        try {
            return new TCPClient(socketChannel, file);
        } catch (Exception e) {
            System.out.println("异常关闭");
            socketChannel.close();
        }
        return null;
    }
}
